package de.lgohlke.serializer.kryo;

import java.lang.reflect.Array;
import java.nio.ByteBuffer;

import com.esotericsoftware.kryo.serialize.SimpleSerializer;

/**
 * <p>ArraySerializer class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public final class ArraySerializer<T> extends SimpleSerializer<T[]>
{
	private final SimpleSerializer<T>	serializer;
	private final Class<T>				arrayClass;

	/**
	 * <p>Constructor for ArraySerializer.</p>
	 *
	 * @param serializer a {@link com.esotericsoftware.kryo.serialize.SimpleSerializer} object.
	 * @param c a {@link java.lang.Class} object.
	 * @param <T> a T object.
	 */
	public ArraySerializer(SimpleSerializer<T> serializer, Class<T> c)
	{
		this.serializer = serializer;
		this.arrayClass = c;
	}

	/** {@inheritDoc} */
	@Override
	public void write(ByteBuffer buffer, T[] data)
	{
		buffer.putInt(data.length);
		for (int i = 0; i < data.length; i++)
		{
			serializer.write(buffer, data[i]);
		}
	}

	/** {@inheritDoc} */
	@SuppressWarnings("unchecked")
	@Override
	public T[] read(ByteBuffer buffer)
	{
		T[] data = (T[]) Array.newInstance(arrayClass, buffer.getInt());

		for (int i = 0; i < data.length; i++)
		{
			data[i] = serializer.read(buffer);
		}

		return data;
	}
}
